package com.welson.restfultoolx.ui;

import com.intellij.openapi.project.Project;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowFactory;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.ui.content.Content;
import com.intellij.ui.content.ContentFactory;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.awt.*;

/**
 * API列表工具窗口
 * 显示项目中所有的RESTful API
 */
public class ApiListToolWindow {
    
    private static final String TOOL_WINDOW_ID = "RestfulToolX APIs";
    
    private final Project project;
    
    public ApiListToolWindow(@NotNull Project project) {
        this.project = project;
    }
    
    public void show() {
        ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(project);
        ToolWindow toolWindow = toolWindowManager.getToolWindow(TOOL_WINDOW_ID);
        
        if (toolWindow == null) {
            // 创建新的工具窗口
            toolWindow = toolWindowManager.registerToolWindow(TOOL_WINDOW_ID, true, 
                com.intellij.openapi.wm.ToolWindowAnchor.BOTTOM);
            
            // 创建内容
            JComponent content = createContent();
            Content tabContent = ContentFactory.getInstance()
                .createContent(content, "APIs", false);
            toolWindow.getContentManager().addContent(tabContent);
        }
        
        // 显示工具窗口
        toolWindow.show();
    }
    
    private JComponent createContent() {
        JPanel panel = new JPanel(new BorderLayout());
        
        // 创建API列表面板
        ApiListPanel apiListPanel = new ApiListPanel(project);
        panel.add(apiListPanel, BorderLayout.CENTER);
        
        return panel;
    }
    
    /**
     * 工具窗口工厂类
     */
    public static class Factory implements ToolWindowFactory {
        
        @Override
        public void createToolWindowContent(@NotNull Project project, @NotNull ToolWindow toolWindow) {
            ApiListToolWindow apiListToolWindow = new ApiListToolWindow(project);
            JComponent content = apiListToolWindow.createContent();
            
            Content tabContent = ContentFactory.getInstance()
                .createContent(content, "APIs", false);
            toolWindow.getContentManager().addContent(tabContent);
        }
    }
}